<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/15
 * Time: 14:30
 */
namespace app\common\lib\redis;

class Predis
{
    public $redis = '';
    /**
     * 定义单例模式的变量
    */
    private static $_instance = null;

    private function __construct()
    {
        $this->redis = new \Redis();
        $result = $this->redis->connect(config('redis.host'), config('redis.port'), config('redis.timeOut'));
        if($result === false){
            throw new \Exception('redis connect error');
        }
        $this->redis->auth(config('redis.password'));
    }


    public static function getInstance()
    {
        if(empty(self::$_instance)){
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function set($key, $value, $time = 0)
    {
        if(!$key){
            return '';
        }
        if(is_array($value)){
            $value = json_encode($value);
        }
        if(!$time){
            return $this->redis->set($key, $value);
        }
        return $this->redis->setex($key, $time , $value);
    }

    public function get($key)
    {
        if(!$key){
            return '';
        }
        return $this->redis->get($key);
    }

    public function del($key)
    {
        if(!$key){
            return '';
        }
        return $this->redis->del($key);
    }

    /**
     * @todo 添加有序序列
     * @param $key
     * @param $value
     */
    public function sAdd($key, $value)
    {
        return $this->redis->sAdd($key , $value);
    }

    /**
     * @todo 删除有序序列
     * @param $key
     * @param $value
     */
    public function sRem($key, $value)
    {
        return $this->redis->sRem($key, $value);
    }

    /**
     * @todo 返回有序redis里面的元素
     * @param $key
     * @return array
     */
    public function sMembers($key)
    {
        return $this->redis->sMembers($key);
    }

    /**
     * @todo 调用不存在的方法，并且是传入两个参数的情况
     * @param $name
     * @param $arguments
     * @return string
     */
    public function __call($name, $arguments)
    {
        // TODO: Implement __call() method.
        if(count($arguments) != 2){
            return '';
        }
        return $this->redis->$name($arguments[0], $arguments[1]);
    }
}